#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define LINE_GAP() {                                    \
    putchar('+');                                       \
    for(int ix = 0; ix < ax; ix++) {                    \
        for(int iy = 0; iy < widths[ix] + 2; iy++) {    \
            putchar('-');                               \
        }                                               \
        putchar('+');                                   \
    }                                                   \
    putchar('\n');                                      \
}

int main(void) {
    int t;
    scanf("%d", &t);
    for(int i = 0; i < t; i++) {
        int ax, ay;
        scanf("%d%d", &ay, &ax);
        char format[20];
        scanf(" %s", format);
        // BREAKPOINT BELOW
        char grids[ay][ax][21];
        for(int iy = 0; iy < ay; iy++) {
            for(int ix = 0; ix < ax; ix++) {
                scanf(" %s", grids[iy][ix]);
            }
        }
        int widths[ax];
        for(int ix = 0; ix < ax; ix++) {
            int max = 0;
            for(int iy = 0; iy < ay; iy++) {
                int len = strlen(grids[iy][ix]);
                if (len > max) {
                    max = len;
                }
            }
            widths[ix] = max;
        }
        
        LINE_GAP();
        
        for(int iy = 0; iy < ay; iy++) {\
            putchar('|');
            for(int ix = 0; ix < ax; ix++) {
                int width = widths[ix] + 2;
                int len = strlen(grids[iy][ix]);
                int left = 0;
                int right = 0;
                int spaces;
                switch(format[ix]) {
                    case 'l':
                        left = 1;
                        right = width - len - left;
                        break;
                    case 'c':
                        spaces = width - len;
                        left = spaces / 2;
                        right = spaces - left;
                        break;
                    case 'r':
                        right = 1;
                        left = width - len - right;
                        break;
                }
                for(int il = 0; il < left; il++) {
                    putchar(' ');
                }
                printf("%s", grids[iy][ix]);
                for(int ir = 0; ir < right; ir++) {
                    putchar(' ');
                }
                putchar('|');
            }
            putchar('\n');
            LINE_GAP();
        }
    }
    return 0;
}
